import React, { useState, useEffect } from 'react';
import {
    View, Image, TextInput, TouchableOpacity, Keyboard, Modal as ModalRN, ScrollView, Text, Toast,
} from 'react-native';
import { launchCamera, launchImageLibrary } from 'react-native-image-picker';
import {
    WingBlank, Modal, Button, WhiteSpace,
} from '@ant-design/react-native';
import ImageViewer from 'react-native-image-zoom-viewer';
import PropTypes from 'prop-types';
import AntDesign from 'react-native-vector-icons/AntDesign';
import styles from './styles';
import { addPlan as addPlanSQL, editPlan, planDetail } from '../../comconfig/sqlfun';
import { debounce } from '../../utils/common';

const options = {
    mediaType: 'photo',
    cameraType: 'back',
    saveToPhotos: true,
    selectionLimit: 1,
};

const AddPlan = ({ navigation, route }) => {
    const [imgUri, setImgUri] = useState([]);
    const [show, setShow] = useState(false);
    const [titleVal, onChangeTitleVal] = useState('');
    const [textVal, onChangeTextVal] = useState('');
    const [images, setImages] = useState([]);
    const [visible, setVisible] = useState(false);
    const [viewPage, setViewPage] = useState(0);
    const { funList, objItem, planid } = route.params;
    const [info, setInfo] = useState({});
    const getDetail = async (id) => {
        try {
            const list = await planDetail(id);
            setInfo(JSON.parse(list));
        } catch (error) {
            Toast.info('获取数据失败', 1, undefined, false);
        }
    };
    useEffect(() => {
        if (planid !== undefined) {
            getDetail(parseInt(planid, 10));
        }
    }, []);
    useEffect(() => {
        if (JSON.stringify(info) !== '{}') {
            onChangeTitleVal(info.title);
            onChangeTextVal(info.detail);
            if (info.img1uri !== null) {
                imgUri.push(info.img1uri);
                images.push({ url: info.img1uri });
            }
            if (info.img2uri !== null) {
                imgUri.push(info.img2uri);
                images.push({ url: info.img2uri });
            }
        }
    }, [info]);
    const addImage = async (type) => {
        if (type === 'camera') {
            const resFromCamera = await launchCamera(options);
            const { uri } = resFromCamera.assets[0];
            setImgUri([...imgUri, uri]);
            setImages([...images, { url: uri }]);
        }
        if (type === 'library') {
            const resFromLib = await launchImageLibrary(options);
            const { uri } = resFromLib.assets[0];
            setImgUri([...imgUri, uri]);
            setImages([...images, { url: uri }]);
        }
    };
    const delIamge = (i) => {
        Modal.operation([
            {
                text: '删除',
                onPress: () => {
                    const copyImages = [...images];
                    copyImages.splice(i, 1);
                    const copyImgUri = [...imgUri];
                    copyImgUri.splice(i, 1);
                    setImgUri(copyImgUri);
                    setImages(copyImages);
                },
                style: { color: '#0F8DE9' },
            },
        ]);
    };
    const addPlan = () => {
        if (titleVal === '' || titleVal === null || titleVal.trim().length === 0) {
            Modal.alert(
                <Text style={{ color: '#0F8DE9' }}>你的计划怎么是空的呢？</Text>,
                null,
                [
                    { text: 'OK' },
                ],
            );
            return;
        }
        if (objItem !== undefined) {
            editPlan(parseInt(objItem.planid, 10), titleVal, textVal, imgUri);
        } else {
            addPlanSQL(titleVal, textVal, imgUri);
        }
        funList.getPlanList();
        navigation.goBack();
    };
    navigation.setOptions({
        headerRight: () => (
            <TouchableOpacity
                onPress={() => debounce(() => {
                    addPlan(titleVal, textVal, imgUri);
                })}
            >
                <AntDesign
                    name="form"
                    size={26}
                    color="#017BFF"
                    style={{ marginRight: 5 }}
                />
            </TouchableOpacity>
        ),
    });
    return (
        <View style={{ flex: 1 }}>
            <TouchableOpacity
                onPress={() => { Keyboard.dismiss(); }}
                activeOpacity={1}
            >
                <ScrollView>
                    <WingBlank>
                        <TextInput
                            placeholder="计划"
                            placeholderTextColor="#5d5d7e"
                            style={{
                                height: 60, borderColor: 'gray', borderWidth: 0, fontSize: 30,
                            }}
                            onChangeText={
                                text => onChangeTitleVal(text)
                            }
                            value={titleVal}
                        />
                        <TextInput
                            multiline
                            placeholder="添加描述..."
                            placeholderTextColor="#5d5d7e"
                            style={styles.textInput}
                            maxLength={200}
                            onChangeText={text => onChangeTextVal(text)}
                            value={textVal}
                            returnKeyLabel="done"
                        />
                        {imgUri.length === 0 ? null : (
                            <View style={{
                                flexDirection: 'row',
                                flexWrap: 'wrap',
                                // justifyContent: 'space-around',
                            }}
                            >

                                {
                                    imgUri.map((uri, i) => (
                                        <TouchableOpacity
                                            key={uri}
                                            onPress={() => { setVisible(true); setViewPage(i); }}
                                            onLongPress={() => delIamge(i)}
                                        >
                                            <Image
                                                style={styles.image}
                                                // resizeMethod
                                                resizeMode="contain"
                                                source={{
                                                    uri,
                                                }}
                                                defaultSource={
                                                    require('../../assets/images/notfound.jpeg')
                                                }
                                            />
                                        </TouchableOpacity>
                                    ))
                                }
                            </View>
                        )}
                        <WhiteSpace />
                        <Button
                            type="primary"
                            onPress={() => { setShow(true); }}
                            disabled={imgUri.length === 2}
                        >
                            {`添加图片${imgUri.length}/2`}
                        </Button>
                    </WingBlank>
                    <Modal
                        popup
                        visible={show}
                        animationType="slide-up"
                        maskClosable
                        onClose={() => setShow(false)}
                    >
                        <Button
                            style={{ borderWidth: 0 }}
                            onPress={() => { addImage('camera'); setShow(false); }}
                        >
                            拍摄
                        </Button>
                        <Button
                            style={{ borderWidth: 0 }}
                            onPress={() => { addImage('library'); setShow(false); }}
                        >
                            从相册选择
                        </Button>
                        <Button
                            style={{ borderWidth: 0 }}
                            onPress={() => setShow(false)}
                        >
                            取消
                        </Button>
                    </Modal>
                    <ModalRN visible={visible}>
                        <ImageViewer imageUrls={images} index={viewPage} />
                        <Button
                            style={{ borderWidth: 0 }}
                            onPress={() => setVisible(false)}
                        >
                            取消
                        </Button>
                    </ModalRN>
                </ScrollView>
            </TouchableOpacity>
        </View>
    );
};
AddPlan.defaultProps = {
    route: {},
};
AddPlan.propTypes = {
    route: PropTypes.objectOf(PropTypes.any),
};
export default AddPlan;
